<template>
    <div class="channel-edit">
        <van-cell>
      <template #title><span class="title-text">我的频道</span>  </template>
      <van-button type="danger" round size="mini" plain class="edit-btn" @click="isEdit = !isEdit">{{ isEdit ? '完成' : '编辑' }}</van-button>
    </van-cell>
    <van-grid :gutter="10" class="my-grid">
      <van-grid-item v-for="(item, index) in channels" :key="index"  class="grid-item" @click="onMyChannelClick(item, index)">
        <template #default>
            <van-icon name="clear" v-show="isEdit && !fixChannels.includes(item.id)"></van-icon>
        <span class="text" :class="{ active: index === channelsId - 1 }">{{ item.name }}</span>
        </template>
        
    </van-grid-item>
    </van-grid>
    <van-cell>
      <template #title> <span class="title-text">频道推荐</span> </template>
      
    </van-cell>
    <van-grid :gutter="10" class="recommend-grid">
      <van-grid-item v-for="(item, indexd) in recomputed" :key="index" :text="item.name"  class="grid-item"   icon="plus" @click="addchann(item)"/>
    </van-grid>

    </div>
    </template>

<script setup>
import { useUsersStore } from "../store/home"
import { storeToRefs } from "pinia"
import { onMounted, computed, reactive, toRefs } from "vue";

let store = useUsersStore()
let { channels, channelsId } = storeToRefs(store)
let ress = reactive({
    isEdit: false,
    fixChannels: [1]
})
let { isEdit, fixChannels } = toRefs(ress)
//计算属性
let recomputed = computed(() => {
    let tjChannels = []
    store.allChannels.forEach((item) => {
        let findz = store.channels.find((item1) => {
            return item1.id == item.id
        })
        if (!findz) {
            tjChannels.push(item)
        }
    })
    return tjChannels
})
//添加频道
function addchann(val) {
    store.channels.push(val)

}

function onMyChannelClick(val, index) {
    // console.log(index)
    if (ress.isEdit) {
        if (ress.fixChannels.includes(val.id)) {
            return
        }
        store.channels.splice(index, 1)
    } else {
        //不在编辑的情况下，点击切换
        store.active = index
        store.show = false
        store.channelsId = index + 1

    }
}
onMounted(() => {
    store.getAllChannels()
})
</script>

<style scoped>
.channel-edit {
    padding: 150px 0
}

.channel-edit .title-text {
    font-size: 30px;
    color: #333;
}

.channel-edit .edit-btn {
    width: 100px;
    height: 50px;
    font-size: 16px;
}

.grid-item {
    background-color: #f4f5f6;
}
</style>